<template>
    <div class="page" style="width: 100%">
        <a-spin :spinning="spinning" style="width: 100%; height: 100vh; max-height: none">
        <!-- 标题 -->
        <div class="title flexBetweenCenter" v-if="renderFlag">
            <div style="color: #fff" class="ml-20">
                {{ fileName }}
            </div>
            <a-button ghost @click="onSubmit" style="margin-right: 60px; color: #fff">提交签署</a-button>
        </div>
        <div class="content flexBetween" v-if="renderFlag">
            <!-- 验签 -->
            <div class="checkSign flexStart">
                <div style="width: 44px; height: 100%; background: #f5f7f9">
                    <div class="pen" @click="onDetail">
                        <img src="../../assets/sign/pen.png" alt="" />
                    </div>
                </div>
                <transition-group name="left">
                    <div v-if="checkDetailFlag" class="checkDetail">
                        <div class="flexBetweenCenter mb-20">
                            <div style="width: 50px">签名</div>
                            <div style="cursor: pointer">
                                <img src="../../assets/sign/cha.png" alt="" @click="onClose" />
                            </div>
                        </div>
                        <div class="mb-10">
                            <a-button type="primary" size="small">验证签名</a-button>
                        </div>
                        <div class="line"></div>
                        <a-collapse v-model:activeKey="activeKey" :bordered="false">
                            <template #expandIcon="{ isActive }">
                                <myIcon type="caret-right-outlined" :rotate="isActive ? 45 : 0" />
                            </template>
                            <a-collapse-panel :header="item.sealName" v-for="(item, index) in signCheckList"
                                :key="index" class="signCheckList">
                                <div class="flexStartCenter" style="color: #00c3a0" v-if="item.certValid == '0'">
                                    <div>
                                        <img src="../../assets/sign/youxiao.png" alt=""
                                            style="vertical-align: -1px; margin-right: 2px" />
                                    </div>
                                    <div>签名有效</div>
                                </div>
                                <div class="flexStartCenter" style="color: #f22424" v-if="item.type == '2'">
                                    <div>
                                        <img src="../../assets/sign/weitongguo.png" alt=""
                                            style="vertical-align: -1px; margin-right: 2px" />
                                    </div>
                                    <div>签名未通过</div>
                                </div>
                                <div class="flexStartCenter" style="color: #f6ae21" v-if="item.type == '1'">
                                    <div>
                                        <img src="../../assets/sign/weizhi.png" alt=""
                                            style="vertical-align: -1px; margin-right: 2px" />
                                    </div>
                                    <div>签名有效性未知</div>
                                </div>
                                <p>由“{{ item.signer ? item.signer : "未知" }}”签名 </p>
                                <p>自签名以来，文档{{ item.isTamper == '1' ? '被修改' : "未被修改" }}</p>
                                <p>签名者身份{{ item.certValid == '0' ? "有效" : item.certValid == '1' ? '未知' : "无效" }}</p>
                                <p>签名时间：{{ item.signDate ? item.signDate : "" }}</p>
                                <p>文档位置：第{{ item.page ? item.page : " " }}页</p>
                            </a-collapse-panel>
                        </a-collapse>
                    </div>
                </transition-group>
            </div>
            <!-- 文件区域 -->
            <div class="pdfDiv" id="pdfDiv" ref="pdfDiv" @scroll.passive="getScroll">
                <div v-for="item in imgList" :key="item.imgId" style="margin-bottom: 20px" :id="item.imgId"
                    class="imgDiv">
                    <img :src="'data:image/Jpeg;base64,' + item.imgByte" alt="" style="width: 100%" draggable="false" />
                    <div class="signListItemPre" v-for="(signItem, index) in item.pdfSignList" :key="signItem.id"
                        :style="{
                            top: `${signItem.y}px`,
                            left: `${signItem.x}px`,
                            'z-index': `${signItem.zIndex}`,
                        }">
                        <!-- 签名 -->
                        <FreeDrag class="signDiv" v-if="signItem.isZoom"
                            :divStyle="{ width: signItem.pictureWidth, height: signItem.pictureHeight }">
                            <img :class="signItem.id" :src="'data:image/Jpeg;base64,' + signItem.sealImage"
                                :pageId="item.imgId" style="width: 100%; height: 100%; cursor: move;object-fit: contain"
                                @mousedown="(e) => mousedown(e, signItem)" @dragstart.prevent @dragover.prevent />
                            <!-- <div style="width: 100%; height: 100%;background: url('../../assets/sign/weizhi.png');background-position:top left" >

                                    </div> -->
                        </FreeDrag>
                        <!-- 印章 -->
                        <div v-else style="border: 2px dashed #1890ff; padding: 5px">
                            <img :class="signItem.id" :src="'data:image/Jpeg;base64,' + signItem.sealImage"
                                :pageId="item.imgId" style="cursor: move"
                                :divStyle="{ width: signItem.pictureWidth, height: signItem.pictureHeight }"
                                @mousedown="(e) => mousedown(e, signItem)" @dragstart.prevent @dragover.prevent />
                        </div>

                        <!-- 删除 -->
                        <div class="closeIcon" @click="delSign(item.pdfSignList, index)">
                            <myIcon type="close-outlined" style="color: #fff" />
                        </div>
                        <!-- 设置日期 -->
                        <!-- <div style="position:absolute;left:0px;top:-27px;"> -->
                        <!-- @click="setDate(signItem)" -->
                        <!-- <myIcon type="drag-outlined" style="color:#1890ff;font-size:25px" /> -->
                        <!-- <a-button type="primary" size="small" style="background:#4F8BFF">拖拽</a-button> -->
                        <!-- </div> -->
                    </div>
                </div>
            </div>
            <!-- 签章列表 -->
            <div class="mySign">
                <a-spin :spinning="signListSpinning" style="width: 100%; height: 100vh; max-height: none">
                    <div style="height: 40px; line-height: 40px; margin-bottom: 10px">
                        我的{{ signType == "0" ? "签名" : "印章" }}
                    </div>
                    <div class="line mb-15" style="width: 150px"></div>
                    <div class="mySignList">
                        <div class="flexCenter addSign" @click="handSign" v-if="signType == '0'">
                            <span style="font-size: 20px">+</span>
                            <span>添加签名</span>
                        </div>
                        <div v-for="item in signList" :key="item.id" :vid="item.id" class="signListItem"
                            :style="signType == '1' ? signature : ''" :name="item.id" draggable="true"
                            @dragstart="(e) => dragstart(e, item)" @dragend="dragend">
                            <img :src="'data:image/Jpeg;base64,' + item.sealImage" alt=""
                                style="width: 100%; height: 100%; object-fit: contain" />
                        </div>
                    </div>
                </a-spin>
            </div>
            <!-- 分页 -->
            <div class="foot flexStartCenter" style="padding-left: 15px; height: 50px; background: #f5f7f9">
                <div class="mr-15">共 {{ pageTotal }} 页</div>
                <a-pagination :current="page" size="small" :total="pageNum(pageTotal)" :page-size="pageSize"
                    @change="pageChange" show-quick-jumper>
                </a-pagination>
            </div>
        </div>
        </a-spin>
        <a-modal title="添加签名" v-model:visible="qrCodevisible" :footer="null" @cancel="signCancel">
            <div style="text-align: center">
                <div class="mb-30">请使用微信扫一扫，扫描下方二维码</div>
                <qrcode-vue :value="qrcodeValue" level="H" :size="200" />
            </div>
        </a-modal>
        <a-modal v-model:visible="dateVisible" :footer="null">
            <p>设置日期</p>
        </a-modal>
        <a-modal v-model:visible="signVisible" title="提示" :centered="true">
            <p style="text-align: center; padding: 20px 0">暂无印章，请联系管理员申请印章</p>
            <template #footer>
                <div style="text-align: center">
                    <a-button type="primary" @click="signVisible = false">我知道了</a-button>
                </div>
            </template>
        </a-modal>
        <a-modal v-model:visible="secondSubmitVisible" title="提示" :centered="true">
            <p style="text-align: center; padding: 20px 0">您已提交签署，请勿重复提交！</p>
            <template #footer>
                <div style="text-align: center">
                    <a-button type="primary" @click="secondSubmitVisible = false">确定</a-button>
                </div>
            </template>
        </a-modal>


        <a-modal v-model:visible="renderVisible" title="提示" :centered="true">
            <p style="text-align: center; padding: 20px 0">调用获取渲染参数失败！</p>
            <template #footer>
                <div style="text-align: center">
                    <a-button type="primary" @click="renderVisible = false">我知道了</a-button>
                </div>
            </template>
        </a-modal>

        <a-modal v-model:visible="uKeyVisible" title="提示" :centered="true">
            <p style="text-align: center; padding: 20px 0">请插入uKey！</p>
            <template #footer>
                <div style="text-align: center">
                    <a-button type="primary" @click="uKeyVisible = false">我知道了</a-button>
                </div>
            </template>
        </a-modal>

        <a-modal v-model:visible="willCertificationVisible" title="意愿认证" :centered="true"
            :confirmLoading="willCertLoading" @ok="willCertSubmit" @cancel="willCertCancel" :maskClosable="false">
            <a-form ref="ruleForm" :model="willForm" :rules="willRules" :label-col="{ span: 4 }"
                :wrapper-col="{ span: 14 }">
                <a-form-item ref="pinCode" label="PIN码" name="pinCode" required>
                    <a-input v-model:value="willForm.pinCode" autocomplete="off" />
                </a-form-item>
            </a-form>

        </a-modal>
    </div>
</template>

<script>
import FreeDrag from "./freeZoom/index.vue";
import QrcodeVue from "qrcode.vue";
import html2canvas from "html2canvas"
import http from "@/utils/request";
import { v4 as uuidv4 } from "uuid"
export default {
    components: { FreeDrag, QrcodeVue, html2canvas },
    data() {
        return {
            //验签展开
            activeKey: [0, 1, 2, 3, 4],
            //柜台1 群众0
            signType: "0",
            //柜台印章大小
            signature: {
                width: "150px",
                height: "150px",
            },
            fileName: "",
            projectId: '3',
            //验签列表
            signCheckList: [

            ],
            //弹出框二维码
            qrCodevisible: false,
            //印章列表
            signList: [],
            //印章列表loading
            signListSpinning: false,
            qrcodeValue: "",
            qrCodeKey: '',
            // 文件图片
            imgList: [],
            // 记录被拖拽元素
            dragItem: null,
            // 记录移动的是哪个签章
            moveItem: null,
            // 鼠标在图片的坐标
            movingNodeOffset: {},
            // loading和分页
            spinning: false,
            page: 1,
            pageSize: 1,
            pageTotal: 0,
            dateVisible: false,

            //验签
            checkDetailFlag: false,

            // 暂无印章标志
            signVisible: false,
            //渲染失败
            renderVisible: false,
            renderFlag: false,

            businessId: "",
            docId: "",
            requestId: "",
            size: 0,
            startRow: 0,
            // 提交签署数据
            imgListSubmit: [],
            sealListSubmit: [],
            submitFlag: false,
            // 获取的图片列表
            imgUrlList: [],
            timer: null,
            secondSubmitVisible: false,

            //定位层级
            zIndex: 0,

            //意愿认证
            willCertificationVisible: false,
            willForm: {
                pinCode: ''
            },
            willRules: {
                pinCode:
                    { required: true, message: '请输入PIN码', trigger: 'blur' }

            },
            //0打开页面前 1提交签署前 2拖动盖章时
            willNode: '',
            //0短信验证码 1刷脸 2ukey 3密码验证
            willType: '',
            willCertLoading: false,
            //ukey证书
            userCert: '',
            //拖动章时的id
            sealCode: '',
            //是否验证成功
            willCertSuccess: false,
            //拖拽放下时的事件对象
            dropEvent: {},
            //ukey的webSocket
            webSocket: '',
            notiCant: '',
            //提示ukey
            uKeyVisible: false,
            //false无ukey true有ukey
            uKeyFlag: true
        };
    },
    created() {
        this.webSocket = new WebSocket("ws://localhost:16088");
        let _this = this
        this.webSocket.onerror = function (e) {
            // _this.uKeyVisible=true;
            _this.uKeyFlag = false;
        };
    },
    mounted() {
        this.businessId = this.$route.query.businessId;
        if (this.businessId) {
            this.requestId = this.$route.query.requestId;
            // 获取渲染参数
            this.getRender();
        } else {
            this.renderVisible = true;
        }
    },
    methods: {
        //获取文件图片
        getFileImg() {
            let data = {
                businessId: this.businessId,
                docId: this.docId,
                requestId: this.requestId,
                size: 0,
                startRow: 0,
            };
            let url = `/open/v1/${this.projectId}/h5Sign/file/getImgs`;
            http.post(url, data).then((res) => {
                if (res.data.code == "1") {
                    res.data.data.forEach((item) => {
                        item.pdfSignList = [];
                    });
                    this.pageTotal = res.data.data.length;
                    this.imgList = res.data.data;
                }
            });
        },

        //获取印章列表
        getSealList() {
            this.signListSpinning = true;
            let data = {
                businessId: this.businessId,
                userCert: "",
                requestId: this.requestId,
            };
            let url = `/open/v1/${this.projectId}/h5Sign/seal/getSealList`;
            http.post(url, data).then((res) => {

                if (res.data.code == "1") {
                    res.data.data.forEach((item) => {
                        item.id = "img" + item.sealId;
                        item.signId = item.sealId;
                        item.pictureWidth = ((item.pictureWidth - 0) * 96) / 25.4 + "px";
                        item.pictureHeight = ((item.pictureHeight - 0) * 96) / 25.4 + "px";
                        item.sealImage = item.sealImage.substring(item.sealImage.lastIndexOf(",") + 1);
                    });

                    this.signList = res.data.data;
                    this.sealCode = this.signList[0].sealId;

                    this.signListSpinning = false;
                } else {
                    this.signListSpinning = false;
                    this.signVisible = true;
                }
            })
        },

        //文件签章
        sealSign() {

            let data = {
                businessId: this.businessId,
                docId: this.docId,
                imgList: this.imgListSubmit,
                requestId: this.requestId,
                sealList: this.sealListSubmit,
            };
            let url = `/open/v1/${this.projectId}/h5Sign/seal/sealSign`;
            http.post(url, data)
                .then((res) => {
                    if (res.data.code == '1') {
                        this.$message.destroy()
                        this.$message.success(res.data.message)
                        this.submitFlag = true
                    }
                    this.spinning = false;
                })
                .catch((err) => {
                    this.spinning = false;

                });
        },

        //文件验签
        sealVerify() {
            let data = {
                downType: 3,
                file: this.docId,
                fileType: 1,
                requestId: this.requestId,
            };
            let url = `/open/v1/${this.projectId}/h5Sign/seal/sealVerify`;
            http.post(url, data).then(res => {
                if (res.data.code == '1') {
                    let data = res.data.data
                    this.signCheckList = data
                    this.checkDetailFlag = true;
                } else {
                    this.$message.destroy()
                    this.$message.error('验签失败');
                }

            })
        },

        //获取渲染参数
        getRender() {
            this.spinning = true;
            let data = {
                businessId: this.businessId,
                requestId: this.requestId,
            };
            let url = `/open/v1/${this.projectId}/h5Sign/url/getRender`;
            http.post(url, data)
                .then((res) => {
                    if (res.data.code == "1") {
                        let response = res.data.data;
                        let fileName = response.fileList[0].fileName;
                        if (fileName) {
                            this.fileName = fileName.substring(0, fileName.lastIndexOf("."));
                        } else {
                            this.fileName = ''
                        }

                        this.docId = response.fileList[0].docId;
                        this.signType = response.sealImageType;
                        this.projectId = response.projectId||3;
                        this.willType = response.willType;
                        this.willNode = response.willNode;
                        if (this.willNode == '0') {
                            this.willForm.pinCode = ''
                            this.willCertificationVisible = true;
                        } else {
                            this.getFileImg();
                            if (this.signType == '1') {
                                this.getSealList();
                                this.connectUkey()
                            } else {
                                this.connect();
                            }

                            this.renderFlag = true;
                            this.spinning = false;
                        }


                    } else {
                        this.spinning = false;
                        this.renderVisible = true;
                    }
                })

        },

        //手动签字
        handSign() {
            this.getQrUrl();
        },
        //关闭
        signCancel() {
            clearTimeout(this.timer);
        },
        //生成二维码链接
        getQrUrl() {
            this.spinning = true;
            let data = {
                businessId: this.businessId,
                requestId: this.requestId,
            };
            let url = `/open/v1/${this.projectId}/h5Sign/url/getQrUrl`;
            http.post(url, data).then((res) => {
                let data = res.data.data;
                
                let signUrl = window.signUrl
                this.qrcodeValue = `${signUrl}/#/?url=${res.data.data.url}&key=${res.data.data.key}&expireTime=${res.data.data.expireTime}&businessId=${this.businessId}`;
              
                this.qrCodeKey = data.key;
                this.timer = setTimeout(() => {
                    this.getQrUrl()
                }, data.expireTime * 1000)
                this.spinning = false;
                this.qrCodevisible = true;
            });
        },
        // 创建长链接
        connect() {
            let web = new WebSocket(window.wsUrl);
            let self = this;

            web.onmessage = (res) => {
                let api = JSON.parse(res.data);

                if (api.bussinessId == self.businessId) {

                    self.imgUrlList.push({
                        img: api.img,
                    });
                    let lastElement = self.imgUrlList[self.imgUrlList.length - 1]
                    let imgBase64 = lastElement.img.substring(lastElement.img.lastIndexOf(",") + 1)
                    if (self.signType == '0') {
                        self.signList.push({
                            signId: self.qrCodeKey,
                            id: self.qrCodeKey,
                            isZoom: 1,
                            pictureWidth: '149px',
                            pictureHeight: '69px',
                            sealImage: imgBase64
                        })
                    }

                    self.qrCodevisible = false;

                } else {

                }
            };

        },

        //连接ukey
        connectUkey() {
            try {
                this.webSocket.send(`{"name":"SOF_GetUserList","id":1} `);
                this.webSocket.onmessage = (res) => {
                    console.log(res);
                    let data = JSON.parse(res.data)
                    if (data.errCode == 0) {
                        if (data.list != "") {
                            this.notiCant = data.list.split("||")[1];
                            console.log(this.notiCant);
                            this.getCert()
                        } else {
                            this.$message.destroy()
                            this.$message.warning("请检测ukey是否已插入");
                        }
                    }
                };
            }
            catch (err) {
                this.uKeyVisible = true;
                this.uKeyFlag = false;
            }
            // this.webSocket.send(`{"name":"SOF_GetUserList","id":1} `);
            // this.webSocket.onerror = function (e) {
            //     _this.uKeyVisible = true;
            //     _this.uKeyFlag = false;
            // };

        },
        //获取证书
        getCert() {
            this.webSocket.send(`{"name":"SOF_ExportUserCert","id":5,"container":"${this.notiCant}"} `);
            this.webSocket.onmessage = (res) => {
                let data = JSON.parse(res.data)
                if (data.errCode == 0) {
                    this.userCert = data.cert;
                }
            };
        },

        //关闭验签
        onClose() {
            this.checkDetailFlag = false;
        },
        //打开验签
        onDetail() {
            if (this.checkDetailFlag == false) {
                this.sealVerify()
            }
        },

        //设置日期
        setDate(obj) {
            this.dateVisible = true;
        },
        //删除签字
        delSign(arr, index) {
            arr.splice(index, 1);
        },

        // freeZoomOk(val,sealItem){
        //     console.log(val);
        //     console.log(sealItem);
        // },
        //滚动条事件
        getScroll(event) {
            if (this.imgList.length > 0) {
                var pdfDiv = document.getElementById("pdfDiv");
                var imgHeight = document.getElementsByClassName("imgDiv");
                var page = Math.round((pdfDiv.scrollTop + pdfDiv.clientHeight) / (imgHeight[0].offsetHeight + 20));
                if (page != this.page) {
                    this.page = page < 1 ? 1 : page;
                    this.page = page > this.pageTotal ? this.pageTotal : page;
                }
                console.log(this.page);
            }
        },

        //提交
        onSubmit() {
            if (this.submitFlag) {
                // 重复提交
                this.secondSubmitVisible = true
            } else {
                // console.log(this.willNode);

                this.spinning = true;
                let sealListSubmit = [];
                let imgListSubmit = [];
                this.imgList.forEach((element) => {
                    element.pdfSignList.forEach((item) => {
                        let imgSign = document.getElementsByClassName(item.id);
                        item.imgWidth = imgSign[0].offsetWidth;
                        item.imgHeight = imgSign[0].offsetHeight;
                        // console.log(item);

                        const config = {
                            useCORS: true,
                            scrollX: 0,
                            scrollY: 0,
                        }
                        html2canvas(imgSign[0], config).then(res => {
                            let imgUrl = res.toDataURL('image/png')
                            // console.log(imgUrl);
                            item.base64 = imgUrl.substring(imgUrl.lastIndexOf(",") + 1)

                        })

                        let sealCode = item.sealId;
                        if (this.signType == '0') {
                            sealCode = item.dropId;
                        }
                        if (item.isZoom) {
                            sealCode = item.dropId;
                        }
                        let sealObj = {
                            page: element.page,
                            sealCode,
                            sealType: this.signType,
                            signProperty: "",
                            x: Math.round(item.x * 10) / 10,
                            y: Math.round(item.y * 10) / 10,
                        };
                        sealListSubmit.push(sealObj);
                        if (item.isZoom) {
                            let imgObj = {
                                img: item.sealImage,
                                imgHeight: (Math.round((item.imgHeight * 25.4) / 96 * 10) / 10).toString(),
                                imgId: item.dropId,
                                signId: item.signId,
                                imgWidth: (Math.round((item.imgWidth * 25.4) / 96 * 10) / 10).toString(),
                            };
                            imgListSubmit.push(imgObj);
                        }
                    });
                });
                this.sealListSubmit = sealListSubmit;
                // 去重
                imgListSubmit = imgListSubmit.filter(function (item, index, self) {
                    return self.findIndex((el) => {

                        return (el.signId == item.signId) && (el.imgWidth == item.imgWidth) && (el.imgHeight == item.imgHeight)


                    }) === index
                })

                this.imgListSubmit = imgListSubmit;
                //文件上有无签章
                if (sealListSubmit.length > 0) {
                    if (this.willNode == '1') {
                        if (this.willType == '2') {
                            if (this.uKeyFlag == false) {
                                //提示无ukey
                                this.uKeyVisible = true;
                            } else {
                                this.willVerify()
                            }

                        } else {
                            this.willForm.pinCode = ''
                            this.willCertificationVisible = true
                        }

                    }
                    else {
                        this.sealSign();
                    }
                } else {
                    this.$message.destroy()
                    this.$message.warning('请先签章')
                    this.spinning = false;
                }



            }


        },

        pageNum(val) {
            if (val == 0) {
                return 1;
            } else {
                return val;
            }
        },
        //页面改变
        pageChange(current, pageSize) {
            this.page = current;
            this.pageSize = pageSize;
            document.getElementsByClassName("imgDiv")[current - 1].scrollIntoView({ block: "start" });
        },
        //拖拽
        dragstart(e, item) {
            this.dragItem = item;
            this.dragItem.vid = e.currentTarget.getAttribute("vid");
            let imgDivDoms = document.querySelectorAll(".imgDiv");
            for (let index = 0; index < imgDivDoms.length; index++) {
                // 设置元素的放置行为——移动
                imgDivDoms[index].addEventListener("dragenter", this.dragenter);
                // 在目标元素经过 必须要阻止默认行为 否则不能触发drop
                imgDivDoms[index].addEventListener("dragover", this.dragover);
                // 离开目标元素时设置元素的放置行为——不能拖放
                imgDivDoms[index].addEventListener("dragleave", this.dragleave);
                // 拖动元素在目标元素松手时添加元素到画布
                imgDivDoms[index].addEventListener("drop", this.drop);
            }
        },
        dragend(e) {
            let imgDivDoms = document.querySelectorAll(".imgDiv");
            for (let index = 0; index < imgDivDoms.length; index++) {
                imgDivDoms[index].removeEventListener("dragenter", this.dragenter);
                imgDivDoms[index].removeEventListener("dragover", this.dragover);
                imgDivDoms[index].removeEventListener("dragleave", this.dragleave);
                imgDivDoms[index].removeEventListener("drop", this.drop);
            }
        },
        dragenter(e) {
            e.dataTransfer.dropEffect = "move";
        },
        dragover(e) {
            e.preventDefault();
        },
        dragleave(e) {
            e.dataTransfer.dropEffect = "none";
        },
        //放下
        drop(e) {

            const { sealImage, sealId, pictureHeight, pictureWidth, signId, isZoom } = this.dragItem;
            this.dropEvent = e
            if (this.willNode == '2') {
                this.willForm.pinCode = ''
                this.willCertificationVisible = true;
            } else {
                let index = this.imgList.findIndex(function (o) {
                    return o.imgId == e.currentTarget.getAttribute("id");
                });
                let obj = this.imgList[index];
                this.zIndex++
                obj.pdfSignList.push({
                    y: e.offsetY - (pictureHeight.replace("px", "") - 0) / 2,
                    x: e.offsetX - (pictureWidth.replace("px", "") - 0) / 2,
                    zIndex: this.zIndex,
                    id: "img" + new Date().getTime().toString(),
                    sealImage,
                    sealId,
                    dropId: uuidv4(),
                    signId,
                    isZoom,
                    pictureWidth,
                    pictureHeight,
                    page: index + 1,
                });

                this.dragItem = null;
            }

        },
        mousedown(e, item) {
            this.moveItem = item;

            //获取x坐标和y坐标
            let x = e.clientX;
            let y = e.clientY;

            //获取左部和顶部的偏移量
            let l = e.target.offsetLeft;
            let t = e.target.offsetTop;

            // 鼠标点击图片的位置
            this.movingNodeOffset = {
                offsetX: e.offsetX,
                offsetY: e.offsetY,
                x, y, l, t,
                pageId: e.target.getAttribute('pageId')
            };

            // console.log(e.target.getAttribute('imgId'));

            document.addEventListener("mousemove", this.mousemove);
            document.addEventListener("mouseup", this.mouseup);
        },
        mousemove(e) {
            const _this = this;
            let imgDivDoms = document.querySelectorAll(".imgDiv");
            let { clientX, clientY } = e;
            let { x, y, l, t, pageId } = this.movingNodeOffset
            let pageIndex = this.imgList.findIndex(function (o, index) {
                return o.imgId == pageId
            });

            // let obj = this.imgList[pageIndex];
            this.imgList[pageIndex].pdfSignList = this.imgList[pageIndex].pdfSignList.map((node, index) => {
                // let moveIdx = obj.pdfSignList.findIndex(function (o) {
                //     return o.id == _this.moveItem.id;
                // });
                // console.log(moveIdx);
                var oDiv = imgDivDoms[pageIndex];
                let Rect = oDiv.getBoundingClientRect();
                //签字的坐标

                let top = clientY - Rect.y - _this.movingNodeOffset.offsetY - 5;
                let left = clientX - Rect.x - _this.movingNodeOffset.offsetX - 5;

                //文件图片的宽高
                let pdfDivHeight = window.getComputedStyle(oDiv).height.replace("px", "") - 0;
                let pdfDivWidth = window.getComputedStyle(oDiv).width.replace("px", "") - 0;
                // console.log(_this.moveItem.id);
                let imgDom = document.getElementsByClassName(_this.moveItem.id)[0];
                let imgHeight = window.getComputedStyle(imgDom).height.replace("px", "") - 0;
                let imgWidth = window.getComputedStyle(imgDom).width.replace("px", "") - 0;

                // 坐标最大范围
                let xMax = pdfDivWidth - imgWidth;
                let yMax = pdfDivHeight - imgHeight;
                top = top < 0 ? 0 : top;
                top = top > yMax ? yMax : top;

                left = left < 0 ? 0 : left;
                left = left > xMax ? xMax : left;

                if (node.id == _this.moveItem.id) {
                    return {
                        ...node,
                        x: left,
                        y: top
                    }
                } else {
                    return node
                }

            })




        },
        mouseup(e) {
            document.removeEventListener("mousemove", this.mousemove);
            document.removeEventListener("mouseup", this.mouseup);
        },

        // 
        //验证PIN码
        willVerify() {
            this.willCertLoading = true
            let data = {
                businessId: this.businessId,
                pinCode: this.willForm.pinCode,
                sealCode: this.sealCode,
                requestId: this.requestId,
                userCert: this.userCert,
            };
            let url = `/open/v1/${this.projectId}/h5Sign/url/willVerify`;
            http.post(url, data).then(res => {
                this.willCertLoading = false
                if (res.data.code == '1') {
                    this.willCertificationVisible = false;
                    if (this.willNode == '0') {
                        this.getFileImg();
                        if (this.signType == '1') {
                            this.getSealList();
                        } else {
                            this.connect();
                        }

                        this.renderFlag = true;
                        this.spinning = false;
                    } else if (this.willNode == '2') {
                        const { sealImage, sealId, pictureHeight, pictureWidth, signId, isZoom } = this.dragItem;
                        let e = this.dropEvent
                        let index = this.imgList.findIndex(function (o) {
                            return o.imgId == e.currentTarget.getAttribute("id");
                        });
                        let obj = this.imgList[index];
                        this.zIndex++
                        obj.pdfSignList.push({
                            y: e.offsetY - (pictureHeight.replace("px", "") - 0) / 2,
                            x: e.offsetX - (pictureWidth.replace("px", "") - 0) / 2,
                            zIndex: this.zIndex,
                            id: "img" + new Date().getTime().toString(),
                            sealImage,
                            sealId,
                            dropId: uuidv4(),
                            signId,
                            isZoom,
                            pictureWidth,
                            pictureHeight,
                            page: index + 1,
                        });

                        this.dragItem = null;
                    } else {
                        this.spinning = true;
                        let sealListSubmit = [];
                        let imgListSubmit = [];
                        this.imgList.forEach((element) => {
                            element.pdfSignList.forEach((item) => {
                                let imgSign = document.getElementsByClassName(item.id);
                                item.imgWidth = imgSign[0].offsetWidth;
                                item.imgHeight = imgSign[0].offsetHeight;
                                // console.log(item);

                                const config = {
                                    useCORS: true,
                                    scrollX: 0,
                                    scrollY: 0,
                                }
                                html2canvas(imgSign[0], config).then(res => {
                                    let imgUrl = res.toDataURL('image/png')
                                    // console.log(imgUrl);
                                    item.base64 = imgUrl.substring(imgUrl.lastIndexOf(",") + 1)

                                })

                                let sealCode = item.sealId;
                                if (this.signType == '0') {
                                    sealCode = item.dropId;
                                }
                                if (item.isZoom) {
                                    sealCode = item.dropId;
                                }
                                let sealObj = {
                                    page: element.page,
                                    sealCode,
                                    sealType: this.signType,
                                    signProperty: "",
                                    x: Math.round(item.x * 10) / 10,
                                    y: Math.round(item.y * 10) / 10,
                                };
                                sealListSubmit.push(sealObj);
                                if (item.isZoom) {
                                    let imgObj = {
                                        img: item.sealImage,
                                        imgHeight: (Math.round((item.imgHeight * 25.4) / 96 * 10) / 10).toString(),
                                        imgId: item.dropId,
                                        signId: item.signId,
                                        imgWidth: (Math.round((item.imgWidth * 25.4) / 96 * 10) / 10).toString(),
                                    };
                                    imgListSubmit.push(imgObj);
                                }
                            });
                        });
                        this.sealListSubmit = sealListSubmit;
                        // 去重
                        imgListSubmit = imgListSubmit.filter(function (item, index, self) {
                            return self.findIndex((el) => {

                                return (el.signId == item.signId) && (el.imgWidth == item.imgWidth) && (el.imgHeight == item.imgHeight)


                            }) === index
                        })

                        this.imgListSubmit = imgListSubmit;
                        // console.log(this.imgList);
                        if (sealListSubmit.length > 0) {
                            this.sealSign();
                        } else {
                            this.$message.destroy()
                            this.$message.warning('请先签章')
                            this.spinning = false;
                        }
                    }
                } else {

                }


            })
        },

        //提交PIN码
        willCertSubmit() {
            this.$refs.ruleForm.validate()
                .then(() => {
                    this.willVerify()
                })
                .catch((error) => {
                    return false;
                });

        },
        //取消PIN码
        willCertCancel() {
            this.willCertificationVisible = false;
            this.spinning = false;
        },

    },
};
</script>
<style scoped>
.title {
    background: #0170fe;
    height: 46px;
    width: 100%;
    min-width: 1400px;
}

.content {
    width: 100%;
    min-width: 1400px;
    background: #ebecec;
    height: calc(100vh - 46px);
}

.pdfDiv {
    min-width: 800px;
    text-align: center;
    padding-top: 4px;
    height: calc(100vh - 95px);
    overflow: auto;
    background: #ebecec;
    margin-right: 20px;
}

.imgDiv {
    position: relative;
    overflow: hidden;
}

.mySign,
.checkSign {
    background: #f5f7f9;
    padding: 23px;
    padding-top: 10px;
    min-width: 207px;
    height: calc(100vh - 46px);
    overflow: auto;
}

.foot {
    position: absolute;
    width: 100%;
    min-width: 1400px;
    bottom: 0;
    left: 0;
}

.signListItem {
    width: 150px;
    height: 70px;
    margin-bottom: 20px;
    background: #fff;
    border: 1px solid #dcdfe6;
    object-fit: cover;
}

.addSign {
    width: 150px;
    height: 70px;
    margin-bottom: 20px;
    flex-direction: column;
    color: #9da3ac;
    font-size: 14px;
    background: url("../../assets/sign/addKuang.png") no-repeat;
}

.signListItemPre {
    user-select: none;
    background: none;
    /* width: 150px;
    height: 70px; */
    /* border: 1px dashed #1890ff; */
    position: absolute;
    /* padding: 3px; */
}

.closeIcon {
    position: absolute;
    right: -8px;
    top: -12px;
    cursor: pointer;
    background: #4f8bff;
    width: 18px;
    height: 18px;
    line-height: 18px;
    border-radius: 18px;
}

:deep(.content-container) {
    overflow: hidden;
}

:deep(.vdr) {
    position: static;
}

.checkSign {
    padding: 0;
    min-width: 282px;
    margin-right: 20px;
    background: #ebecec;
}

.checkDetail {
    background: #f5f7f9;
    border-left: 1px solid #e4e6ea;
    border-right: 1px solid #e4e6ea;
    width: 238px;
    height: 100%;
    padding: 18px 14px;
}

.pen {
    width: 34px;
    height: 34px;
    background: #dfe4e9;
    margin: 0 auto;
    margin-top: 10px;
    text-align: center;
    border-radius: 5px;
    line-height: 30px;
    cursor: pointer;
}

.left-enter,
.left-leave-to {
    transform: translateX(-100%);
}

.left-leave,
.left-enter-to {
    transform: translateX(0);
}

.left-enter-active,
.left-leave-active {
    transition: all 0.2s;
}

.closeIcon {
    position: absolute;
    left: 0px;
    top: -20px;
    cursor: pointer;
    background: #4f8bff;
    width: 18px;
    height: 18px;
    line-height: 18px;
    border-radius: 18px;
}

:deep(.ant-collapse-borderless > .ant-collapse-item) {
    border: none;
}

.signCheckList p {
    margin: 0;
    font-size: 13px;
}

:deep(.ant-collapse > .ant-collapse-item > .ant-collapse-header) {
    padding-left: 0;
    padding-bottom: 5px;
}

:deep(.ant-collapse > .ant-collapse-item > .ant-collapse-header .ant-collapse-arrow) {
    margin-right: 5px;
    vertical-align: -3px;
}

:deep(.ant-collapse-content > .ant-collapse-content-box) {
    padding-right: 0;
    padding-left: 14px;
}

:deep(.ant-spin-container) {
    width: 100%;
}

:deep(.ant-spin-dot-spin) {
    top: 50%;
}
</style>
